package com.caineng.zhaobiao.zbapi.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.caineng.zhaobiao.zbapi.controller.paramVo.CaiCompanyParam;
import com.caineng.zhaobiao.zbapi.controller.resultVo.CaiCompanyDetail;
import com.caineng.zhaobiao.zbapi.controller.resultVo.CaiCompanySimple;
import com.caineng.zhaobiao.zbapi.dao.*;
import com.caineng.zhaobiao.zbapi.domain.*;
import com.caineng.zhaobiao.zbapi.service.CaiCompanyService;
import com.caineng.zhaobiao.zbapi.service.CaiQualiCompanyService;
import com.caineng.zhaobiao.zbapi.utils.AjaxResult;
import com.caineng.zhaobiao.zbapi.utils.ip.AddressUtils;
import com.caineng.zhaobiao.zbapi.utils.multipleDb.MongodbConfiguration;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 企业服务类
 * @author liandyao
 * @date 2022/7/18 15:46
 */
@Api(tags = "企业信息服务模块")
@RestController
@RequestMapping("/zbapi/company")
@Slf4j
public class CaiCompanyController {

    @Autowired
    CaiCompanyDao companyDao;

    @Autowired
    CaiCompanyBiddingListDao caiCompanyBiddingListDao;

    @Autowired
    CaiCompanyChangeRecordListDao caiCompanyChangeRecordListDao ;

    @Autowired
    CaiCompanyMainStuffListDao caiCompanyMainStuffListDao ;

    @Autowired
    CaiCompanyProjectDetailsListDao caiCompanyProjectDetailsListDao ;

    @Autowired
    CaiCompanyQualificationDetailsListDao caiCompanyQualificationDetailsListDao;

    @Autowired
    CaiCompanyRegisteredPersonnelDetailsListDao caiCompanyRegisteredPersonnelDetailsListDao;

    @Autowired
    CaiCompanyCreditRateListDao caiCompanyCreditRateListDao ;

    @Autowired
    CaiCompanyService companyService ;

    @Autowired
    CaiQualiCompanyService qualiCompanyService ;

    @Autowired
    MongoTemplate mongoTemplate ;

    @Autowired
    CaiQualiCompanyDao caiquiCompanyDao;

    @Autowired
    @Qualifier(MongodbConfiguration.MONGO_TEMPLATE_SECONDARY)
    MongoTemplate mongoTemplateSecondary ;

    @Autowired
    HttpServletRequest request;




    @GetMapping("/findAll")
    @ApiOperationSupport(order = 100)
    @ApiOperation(value = "001 查询所有的企业信息")
    public AjaxResult findAll(CaiCompanyParam zb){


        long start = System.currentTimeMillis();

        Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize());

        /*CaiCompany company = new CaiCompany();

        BeanUtils.copyProperties(zb,company);
        //模糊查询
        ExampleMatcher matcher=ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<CaiCompany> ex = Example.of(company,matcher);

        Page<CaiCompany> records = companyDao.findAll(ex,page);
        */
        List<CaiCompanySimple> listQua = qualiCompanyService.findAll(zb,page);

        //List<CaiCompany> list = companyService.findAll(zb,page);

        Page records = new PageImpl(listQua,page,1000);

        long end = System.currentTimeMillis();
        log.info("---经过的时间是--->"+(start-end)/1000);
        return AjaxResult.success("成功",records);

    }

    @GetMapping("/findAllMore")
    @ApiOperationSupport(order = 150)
    @ApiOperation(value = "0020 查询更多的企业信息,从大库里面查询")
    public AjaxResult findAllMore(CaiCompanyParam zb){
        long start = System.currentTimeMillis();

        Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize());
        List<CaiCompanySimple> list = companyService.findAll(zb,page);

        Page records = new PageImpl(list,page,1000);

        long end = System.currentTimeMillis();
        log.info("---经过的时间是--->"+(start-end)/1000);
        return AjaxResult.success("成功",records);

    }


    @GetMapping("/findOnlyCompanyName")
    @ApiOperationSupport(order = 202)
    @ApiOperation(value = "202 精确查询企业名称,不查询曾用名,不排序 ")
    public AjaxResult findOnlyCompanyName(String name){
        long start = System.currentTimeMillis();

        Pageable page = PageRequest.of(0, 10);
        Query query = new Query();
        query.addCriteria(Criteria.where("companyName").is(name));
        //List<CaiCompany> list = companyService.findAll(zb,page);
        //查询指定的字段
        query.with(page).fields().include("companyCid").include("companyName").include("companyHistoryNames");
        List<Map> list = mongoTemplate.find(query, Map.class,"cai_quali_company");

        //如果查询不到,查询大库
        if(list.isEmpty()){
            list=mongoTemplateSecondary.find(query, Map.class,"cai_company");
        }

        Page records = new PageImpl(list,page,1000);
        long end = System.currentTimeMillis();
        log.info("---经过的时间是--->"+(start-end)/1000);
        return AjaxResult.success("成功",records);

    }


    /**
     * 普通查询,不按照地理位置的查询
     * @param name
     * @return
     */
    public AjaxResult findCompanyName2(String name){
        long start = System.currentTimeMillis();

        Pageable page = PageRequest.of(0, 10,Sort.by(Sort.Order.desc("companyRegisteredPersonnelDetailsListSize")));
        Query query = new Query();
        Criteria criteria = new Criteria();
        Pattern pattern = Pattern.compile("^.*" + name + ".*$"); //拼接 正则表达式和查询参数

        criteria.orOperator(Criteria.where("companyName").is(pattern) ,Criteria.where("companyHistoryNames").is(pattern));
        query.addCriteria(criteria);
        //List<CaiCompany> list = companyService.findAll(zb,page);
        //查询指定的字段
        query.with(page).fields().include("companyName").include("companyHistoryNames");
        List<Map> list = mongoTemplate.find(query, Map.class,"cai_quali_company");

        //如果查询不到,查询大库
//        if(list.isEmpty()){
//            list=mongoTemplateSecondary.find(query, Map.class,"cai_company");
//        }

        Page records = new PageImpl(list,page,1000);
        long end = System.currentTimeMillis();
        log.info("---经过的时间是--->"+(start-end)/1000);
        return AjaxResult.success("成功",records);

    }

    @GetMapping("/findCompanyName")
    @ApiOperationSupport(order = 201)
    @ApiOperation(value = "201 查询企业的名称GEO,如果没有ip信息,则从上面的方法查询")
    public AjaxResult findCompanyName(String name){
        /*String ipAddress = AddressUtils.getRealAddressByIP_GEO(request);

        //如果没有ip
        if(StrUtil.isBlank(ipAddress)){
            return findCompanyName2(name);
        }
        log.info("根据ip查询地区:"+ipAddress);

        //根据ip得到的地址查询经纬度
        Map map = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(ipAddress)),Map.class,"cai_address_geo");
        double lng = (double) map.get("lng");//经度
        double lat = (double) map.get("lat");//纬度

        Criteria criteria = new Criteria();
        Pattern pattern = Pattern.compile("^.*" + name + ".*$"); //拼接 正则表达式和查询参数

        criteria.orOperator(Criteria.where("companyName").is(pattern) ,Criteria.where("companyHistoryNames").is(pattern));

        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.geoNear(NearQuery.near(lng,lat, Metrics.KILOMETERS).spherical(true),"distance"),
                Aggregation.match(criteria),
                Aggregation.limit(10)
        );
        AggregationResults result = mongoTemplate.aggregate(aggregation,"cai_quali_company_geo",Map.class);
        List list =result.getMappedResults();

        Page records = new PageImpl(list);*/
        return findCompanyName2(name);

    }

    //查询企业排行信息

    /**
     * 查询前100个,然后随机取10个显示在页面上
     * @param companyProvince
     * @param companyCity
     * @param qualification
     * @return
     */
    @ApiOperationSupport(order = 300)
    @GetMapping("/findCompanyRankingList")
    @ApiOperation(value = "0030 查询企业排行信息",notes = "请输入qualification的参数查询: jianZhu , sheJi , sheJi_shiGong , zaoJia")
    public AjaxResult findCompanyRankingList(String companyProvince,String companyCity,String qualification){
        long start = System.currentTimeMillis();
        log.info(companyProvince+"  查询的城市  "+companyCity);
        Pageable page = PageRequest.of(0, 100,Sort.by(Sort.Order.desc("companyRegisteredPersonnelDetailsListSize")));
        Query query = new Query();
        if(StrUtil.isNotBlank(companyProvince)){
            Criteria criteria = Criteria.where("companyProvince").is(companyProvince);
            query.addCriteria(criteria);
        }
        if(StrUtil.isNotBlank(companyCity)){
            Criteria criteria2 =  Criteria.where("companyCity").is(companyCity) ;
            query.addCriteria(criteria2);
        }

        if(StrUtil.isNotBlank(qualification)){
            Criteria criteria2 =  Criteria.where("qualification").in(qualification) ;
            query.addCriteria(criteria2);
        }
        //查询指定的字段
        query.with(page).fields().include("companyName").include("companyCid");

        List<CaiCompanySimple> list = mongoTemplate.find(query, CaiCompanySimple.class,"cai_quali_company");
        List<CaiCompanySimple> randList = RandomUtil.randomEleList(list,10);

        Page records = new PageImpl(randList,page,10);

        long end = System.currentTimeMillis();

        log.info("---查询企业排行榜信息的时间是--->"+(start-end)/1000);
        return AjaxResult.success("成功",records);

    }

    /**
     * 根据企业id查询企业详情
     * @param companyCid
     * @return
     */
    @ApiOperation(value = "003 根据企业id查询企业详情")
    @GetMapping("/findOne")
    public AjaxResult findOne(String companyCid){
        Assert.notNull(companyCid,"id不能为空");
        if(!companyService.isViewMax()){
            return AjaxResult.maxLimitByDay("今日查看已经达到上限");
        }
        CaiQualiCompany company = new CaiQualiCompany();
        company.setCompanyCid(companyCid);
        CaiQualiCompany c=caiquiCompanyDao.findOne(Example.of(company)).orElse(null);
        //需要返回的对象
        CaiCompanyDetail cd= new CaiCompanyDetail();
        if(c==null){
            //从大数据库中查询
            CaiCompany com = mongoTemplateSecondary.findOne(Query.query(Criteria.where("companyCid").is(companyCid)),CaiCompany.class);
            if(com==null) {
                return AjaxResult.error("找不到该企业");
            }else{

                BeanUtils.copyProperties(com,cd);
            }
        }else{
            //从有资质的企业中查询
            BeanUtils.copyProperties(c,cd);
        }

        //查询企业的中标记录
        CaiCompanyBiddingList companyBidding = new CaiCompanyBiddingList();
        companyBidding.setCompanyCid(companyCid);
        Example<CaiCompanyBiddingList> ex = Example.of(companyBidding);
        List<CaiCompanyBiddingList> records = caiCompanyBiddingListDao.findAll(ex);
        Double money = 0.0 ; //中标金额
        String area = "" ; //中标区域
        Double maxMoney = 0.0 ; // 最大中标金额
        List<String> list = new ArrayList<>() ;
        for(CaiCompanyBiddingList re:records){
            Double theMoney = NumberUtil.parseDouble(re.getCompanyBidAmount());
            money += theMoney ;
            if(maxMoney<theMoney){
                maxMoney = theMoney ;
            }
            if(StrUtil.isNotBlank(re.getCompanyBidArea())) {
                //中标区域
                list.add(re.getCompanyBidArea());
            }
        };
        area=  maxEle(list);
        cd.setSumMoney(money);
        cd.setMaxMoney(maxMoney);
        cd.setBidderAreaName(area);

        //TODO 更新中标次数,暂时先不更新,2022年11月19日,以后更好的方法再更新

        return AjaxResult.success("成功",cd);


    }

    /**
     * 查询集合中出现次数最多的元素
     * @param list
     * @return
     */
    private String maxEle(List<String> list){
        log.info(StrUtil.join(",",list));
        String key = list.stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                .entrySet()
                .stream()
                .max(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .orElse(null);
        log.info("出现频次最高的元素是：" + key);
        return  key ;

    }


    @GetMapping("/findCompanyBiddingList")
    @ApiOperation(value = "查询企业中标信息")
    public AjaxResult findCompanyBiddingList(CaiCompanyParam zb){
        Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize(),Sort.by(Sort.Order.desc("companyBidPubTime")));
        /*CaiCompanyBiddingList company = new CaiCompanyBiddingList();
        company.setCompanyCid(zb.getCompanyCid());
        Example<CaiCompanyBiddingList> ex = Example.of(company);
        Page<CaiCompanyBiddingList> records = caiCompanyBiddingListDao.findAll(ex,page);*/
        Query query = new Query();

        //查id
        if(StrUtil.isNotBlank(zb.getCompanyCid())){
            Criteria criteria =  Criteria.where("companyCid").is(zb.getCompanyCid());
            query.addCriteria(criteria);
        }
        query.with(page);

        List<CaiCompanyBiddingList> list = mongoTemplate.find(query, CaiCompanyBiddingList.class);
        if(list.isEmpty()){
            list = mongoTemplateSecondary.find(query,CaiCompanyBiddingList.class);
        }
        Page records = new PageImpl(list,page,1000);

        return AjaxResult.success("成功",records);

    }

    @GetMapping("/findCompanyChangeRecordList")
    @ApiOperation(value = "查询企业变更信息")
    public AjaxResult findCaiCompanyChangeRecordList(CaiCompanyParam zb){
        Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize());
        /*CaiCompanyChangeRecordList company = new CaiCompanyChangeRecordList();
        company.setCompanyCid(zb.getCompanyCid());
        Example<CaiCompanyChangeRecordList> ex = Example.of(company);
        Page<CaiCompanyChangeRecordList> records = caiCompanyChangeRecordListDao.findAll(ex,page);*/

        Query query = new Query();

        //查id
        if(StrUtil.isNotBlank(zb.getCompanyCid())){
            Criteria criteria =  Criteria.where("companyCid").is(zb.getCompanyCid());
            query.addCriteria(criteria);
        }
        query.with(page);

        List<CaiCompanyChangeRecordList> list = mongoTemplate.find(query, CaiCompanyChangeRecordList.class);
        if(list.isEmpty()){
            list = mongoTemplateSecondary.find(query,CaiCompanyChangeRecordList.class);
        }
        Page records = new PageImpl(list,page,1000);

        return AjaxResult.success("成功",records);
    }


    @GetMapping("/findCompanyMainStuffList")
    @ApiOperation(value = "查询企业主要人员信息")
    public AjaxResult findCaiCompanyMainStuffList(CaiCompanyParam zb){
       /* Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize());
        CaiCompanyMainStuffList company = new CaiCompanyMainStuffList();
        company.setCompanyCid(zb.getCompanyCid());
        Example<CaiCompanyMainStuffList> ex = Example.of(company);
        Page<CaiCompanyMainStuffList> records = caiCompanyMainStuffListDao.findAll(ex,page);
        return AjaxResult.success("成功",records);*/
        long start = System.currentTimeMillis();
        log.info(JSONUtil.toJsonStr(zb));
        Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize());
        Query query = new Query();

        //查id
        if(StrUtil.isNotBlank(zb.getCompanyCid())){
            Criteria criteria =  Criteria.where("companyCid").is(zb.getCompanyCid());
            query.addCriteria(criteria);
        }

        //按关键字查名称,项目名称
        if(StrUtil.isNotBlank(zb.getCompanyName())){
            Pattern pattern = Pattern.compile("^.*" + zb.getCompanyName() + ".*$"); //拼接 正则表达式和查询参数
            Criteria criteria =  Criteria.where("companyStuffName").regex(pattern) ;
            query.addCriteria(criteria);
        }


        query.with(page);

        List<CaiCompanyMainStuffList> list = mongoTemplate.find(query, CaiCompanyMainStuffList.class);
        if(list.isEmpty()){
            list = mongoTemplateSecondary.find(query,CaiCompanyMainStuffList.class);
        }
        log.info(JSONUtil.toJsonStr(list));
        Page records = new PageImpl(list,page,1000);

        long end = System.currentTimeMillis();
        log.info("---查询企业注册人员信息的时间是--->"+(start-end)/1000);

        return AjaxResult.success("成功",records);

    }


    @GetMapping("/findCompanyProjectDetailsList")
    @ApiOperation(value = "查询企业业绩信息")
    public AjaxResult findCaiCompanyProjectDetailsList(CaiCompanyParam zb){
        /*Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize());
        CaiCompanyProjectDetailsList company = new CaiCompanyProjectDetailsList();
        company.setCompanyCid(zb.getCompanyCid());
        Example<CaiCompanyProjectDetailsList> ex = Example.of(company);
        Page<CaiCompanyProjectDetailsList> records = caiCompanyProjectDetailsListDao.findAll(ex,page);*/
        long start = System.currentTimeMillis();
        log.info(JSONUtil.toJsonStr(zb));
        Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize());
        Query query = new Query();

        //查id
        if(StrUtil.isNotBlank(zb.getCompanyCid())){
            Criteria criteria =  Criteria.where("companyCid").is(zb.getCompanyCid());
            query.addCriteria(criteria);
        }
        //查省份
        if(StrUtil.isNotBlank(zb.getCompanyProvince())){
            Pattern pattern = Pattern.compile("^.*" + zb.getCompanyProvince() + ".*$"); //拼接 正则表达式和查询参数
            Criteria criteria =  Criteria.where("companyBaseInfo.companyBase").regex(pattern) ;
            query.addCriteria(criteria);
        }

        //查城市
        if(StrUtil.isNotBlank(zb.getCompanyCity())){
            Pattern pattern = Pattern.compile("^.*" + zb.getCompanyCity() + ".*$"); //拼接 正则表达式和查询参数
            Criteria criteria =  Criteria.where("companyBaseInfo.companyBase").regex(pattern) ;
            query.addCriteria(criteria);
        }
        //按关键字查名称,项目名称
        if(StrUtil.isNotBlank(zb.getCompanyName())){
            Pattern pattern = Pattern.compile("^.*" + zb.getCompanyName() + ".*$"); //拼接 正则表达式和查询参数
            Criteria criteria =  Criteria.where("companyBaseInfo.companyProName").regex(pattern) ;
            query.addCriteria(criteria);
        }

        //TODO 这里因为关联查询不方便,后续再做企业类型(jianZhu,kanCa,zaoJia)的查询


        query.with(page);

        List<CaiCompanyProjectDetailsList> list = mongoTemplate.find(query, CaiCompanyProjectDetailsList.class);
        if(list.isEmpty()){
            list = mongoTemplateSecondary.find(query,CaiCompanyProjectDetailsList.class);
        }
        Page records = new PageImpl(list,page,1000);

        long end = System.currentTimeMillis();
        log.info("---查询企业业绩信息的时间是--->"+(start-end)/1000);

        return AjaxResult.success("成功",records);
    }

    @GetMapping("/findCompanyQualificationDetailsList")
    @ApiOperation(value = "查询企业资质证书信息")
    public AjaxResult findCaiCompanyQualificationDetailsList(CaiCompanyParam zb){
        Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize());
        /*CaiCompanyQualificationDetailsList company = new CaiCompanyQualificationDetailsList();
        company.setCompanyCid(zb.getCompanyCid());
        Example<CaiCompanyQualificationDetailsList> ex = Example.of(company);
        Page<CaiCompanyQualificationDetailsList> records = caiCompanyQualificationDetailsListDao.findAll(ex,page);*/

        Query query = new Query();

        //查id
        if(StrUtil.isNotBlank(zb.getCompanyCid())){
            Criteria criteria =  Criteria.where("companyCid").is(zb.getCompanyCid());
            query.addCriteria(criteria);
        }
        query.with(page);

        List<CaiCompanyQualificationDetailsList> list = mongoTemplate.find(query, CaiCompanyQualificationDetailsList.class);
        if(list.isEmpty()){
            list = mongoTemplateSecondary.find(query,CaiCompanyQualificationDetailsList.class);
        }
        Page records = new PageImpl(list,page,1000);


        return AjaxResult.success("成功",records);
    }

    @GetMapping("/findCompanyRegisteredPersonnelDetailsList")
    @ApiOperation(value = "查询企业注册人员信息")
    public AjaxResult findCaiCompanyRegisteredPersonnelDetailsList(CaiCompanyParam zb){
       /* Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize());
        CaiCompanyRegisteredPersonnelDetailsList company = new CaiCompanyRegisteredPersonnelDetailsList();
        company.setCompanyCid(zb.getCompanyCid());
        Example<CaiCompanyRegisteredPersonnelDetailsList> ex = Example.of(company);
        Page<CaiCompanyRegisteredPersonnelDetailsList> records = caiCompanyRegisteredPersonnelDetailsListDao.findAll(ex,page);
        return AjaxResult.success("成功",records);*/

        long start = System.currentTimeMillis();
        log.info(JSONUtil.toJsonStr(zb));
        Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize());
        Query query = new Query();

        //查id
        if(StrUtil.isNotBlank(zb.getCompanyCid())){
            Criteria criteria =  Criteria.where("companyCid").is(zb.getCompanyCid());
            query.addCriteria(criteria);
        }
        //查省份
        if(StrUtil.isNotBlank(zb.getCompanyProvince())){
            Pattern pattern = Pattern.compile("^.*" + zb.getCompanyProvince() + ".*$"); //拼接 正则表达式和查询参数
            Criteria criteria =  Criteria.where("companyHumanProject.companyBase").regex(pattern) ;
            query.addCriteria(criteria);
        }

        //查城市
        if(StrUtil.isNotBlank(zb.getCompanyCity())){
            Pattern pattern = Pattern.compile("^.*" + zb.getCompanyCity() + ".*$"); //拼接 正则表达式和查询参数
            Criteria criteria =  Criteria.where("companyHumanProject.companyBase").regex(pattern) ;
            query.addCriteria(criteria);
        }
        //按关键字查名称,项目名称
        if(StrUtil.isNotBlank(zb.getCompanyName())){
            Pattern pattern = Pattern.compile("^.*" + zb.getCompanyName() + ".*$"); //拼接 正则表达式和查询参数
            Criteria criteria =  Criteria.where("companyHumanName").regex(pattern) ;
            query.addCriteria(criteria);
        }

        if(StrUtil.isNotBlank(zb.getQualification())){
            String[] arr = zb.getQualification().split(",");
            Criteria criteria =  Criteria.where("companyRegInfo.companyRegisterType").in(arr) ;
            query.addCriteria(criteria);
        }


        query.with(page);

        List<CaiCompanyRegisteredPersonnelDetailsList> list = mongoTemplate.find(query, CaiCompanyRegisteredPersonnelDetailsList.class);
        if(list.isEmpty()){
            list = mongoTemplateSecondary.find(query,CaiCompanyRegisteredPersonnelDetailsList.class);
        }
        log.info(JSONUtil.toJsonStr(list));
        Page records = new PageImpl(list,page,1000);

        long end = System.currentTimeMillis();
        log.info("---查询企业注册人员信息的时间是--->"+(start-end)/1000);

        return AjaxResult.success("成功",records);

    }


    @GetMapping("/findCompanyCreditRateList")
    @ApiOperation(value = "查询企业税务等级信息")
    public AjaxResult findCaiCompanyCreditRateList(CaiCompanyParam zb){
        Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize());
        /*CaiCompanyCreditRateList company = new CaiCompanyCreditRateList();
        company.setCompanyCid(zb.getCompanyCid());
        Example<CaiCompanyCreditRateList> ex = Example.of(company);
        Page<CaiCompanyCreditRateList> records = caiCompanyCreditRateListDao.findAll(ex,page);*/
        Query query = new Query();

        //查id
        if(StrUtil.isNotBlank(zb.getCompanyCid())){
            Criteria criteria =  Criteria.where("companyCid").is(zb.getCompanyCid());
            query.addCriteria(criteria);
        }
        query.with(page);

        List<CaiCompanyCreditRateList> list = mongoTemplate.find(query, CaiCompanyCreditRateList.class);
        if(list.isEmpty()){
            list = mongoTemplateSecondary.find(query,CaiCompanyCreditRateList.class);
        }
        Page records = new PageImpl(list,page,1000);
        return AjaxResult.success("成功",records);
    }


    @GetMapping("/findNewBidding")
    @ApiOperationSupport(order = 300)
    @ApiOperation(value = "300 查询新中标企业信息---3.0版本使用")
    public AjaxResult findNewBidding(CaiCompanyParam zb){


        long start = System.currentTimeMillis();

        Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize(),Sort.by(Sort.Order.desc("companyRegisteredPersonnelDetailsListSize")));
        Criteria criteria = new Criteria();

        //查询所在城市
        if(StrUtil.isNotBlank(zb.getCompanyCity())){
            Criteria cr=new Criteria();
            cr.and("companyCity").is(zb.getCompanyCity());
            criteria.andOperator(cr);
        }
        //查询所在省份
        if(StrUtil.isNotBlank(zb.getCompanyProvince())){
            Criteria cr=new Criteria();
            cr.and("companyProvince").is(zb.getCompanyProvince());
            criteria.andOperator(cr);
        }

        //根据ip查询
        if(StrUtil.isNotBlank(zb.getCompanyCity())&&StrUtil.isNotBlank(zb.getCompanyProvince())){
            String ipAddress = AddressUtils.getRealAddressByIP_GEO(request);

            if(StrUtil.isNotBlank(ipAddress)){
                String provinceName = ipAddress.split("-")[0];
                criteria=Criteria.where("provinceName").is(provinceName);
            }
        }

        Query query = new Query();
        query.with(page);
        query.addCriteria(criteria).fields().include("companyCid").include("companyName").include("companyBusinessScope").
                include("companyCity").include("companyIndustry").include("companyProvince").
                include("companyRegCapital").include("companyRegLocation").
                include("companyRegStatus").include("companyQualificationDetailsListSize").include("companyHistoryNames") ;


        List<CaiCompanySimple> listQua =  mongoTemplate.find(query,CaiCompanySimple.class,"cai_quali_company");

        //List<CaiCompany> list = companyService.findAll(zb,page);

        Page records = new PageImpl(listQua,page,1000);

        long end = System.currentTimeMillis();
        log.info("---经过的时间是--->"+(start-end)/1000);
        return AjaxResult.success("成功",records);

    }


    @GetMapping("/findNewBidding2")
    @ApiOperationSupport(order = 300)
    @ApiOperation(value = "301 查询新中标企业信息 3.1版本之后使用")
    public AjaxResult findNewBidding2(CaiCompanyParam zb){


        long start = System.currentTimeMillis();

        Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize(),Sort.by(Sort.Order.desc("createTime")));
        Criteria criteria = new Criteria();

        //查询所在城市
        if(StrUtil.isNotBlank(zb.getCompanyCity())){
            Criteria cr=new Criteria();
            cr.and("companyBidCity").is(zb.getCompanyCity());
            criteria.andOperator(cr);
        }
        //查询所在省份
        if(StrUtil.isNotBlank(zb.getCompanyProvince())){
            Criteria cr=new Criteria();
            cr.and("companyBidArea").is(zb.getCompanyProvince());
            criteria.andOperator(cr);
        }

        //根据ip查询
        if(StrUtil.isNotBlank(zb.getCompanyCity())&&StrUtil.isNotBlank(zb.getCompanyProvince())){
            String ipAddress = AddressUtils.getRealAddressByIP_GEO(request);

            if(StrUtil.isNotBlank(ipAddress)){
                String provinceName = ipAddress.split("-")[0];
                criteria=Criteria.where("companyBidArea").is(provinceName);
            }
        }

        Query query = new Query();
        query.with(page);
        query.addCriteria(criteria) ;


        List<CaiCompanyNewBidding> listQua =  mongoTemplate.find(query,CaiCompanyNewBidding.class,"cai_companyNewBidding");

        //List<CaiCompany> list = companyService.findAll(zb,page);

        Page records = new PageImpl(listQua,page,1000);

        long end = System.currentTimeMillis();
        log.info("---经过的时间是--->"+(start-end)/1000);
        return AjaxResult.success("成功",records);

    }


}
